package light.head.controller.site;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.site.IndexAdvertisingAnnexDAO;
import light.head.dao.site.IndexAdvertisingDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.FileInfo;
import light.head.model.IndexAdvertising;
import light.head.model.IndexAdvertisingAnnex;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(Url.INDEXADVERTISING)
public class IndexAdvertisingController extends SupporterController{

	private IndexAdvertisingDAO iaDAO;
	private IndexAdvertisingAnnexDAO iaaDAO;
	private final static String upload_path = "upload/indexAdvertisingAnnex/";
	private final static String indexadvertising_photo_path = "upload/indexAdvertisingPhoto/";
	private final static String indexadvertising_file_path = "upload/indexAdvertisingFile/";
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.INDEX_ADVERTISING_INIT);
	}

	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.TITLE, Parm.PM, Parm.TIME1, Parm.TIME2, Parm.SORT);
		if (iaDAO.findByMap(map, pb) == RESULT.SUCCESS) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.INDEX_ADVERTISING_LIST);
	}

	@RequestMapping(value = Url.DELETE)
	public void delete(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if(code != null){
			IndexAdvertising ia = iaDAO.get(code);
			if(ia != null){
				ia.setDeleted(true);
				result = iaDAO.upd(ia);
			}
		}
		if (result == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}

	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			IndexAdvertising ia = iaDAO.get(Integer.parseInt(code));
			List<IndexAdvertisingAnnex> list = iaDAO.findAnnexByOccCode(Integer.parseInt(code));
			request.setAttribute(Parm.LIST, list);
			request.setAttribute(Parm.IA, ia);
		}
		return new ModelAndView(Url.INDEX_ADVERTISING_EDIT);
	}

	@RequestMapping(value = Url.SAVE)
	public void save(IndexAdvertising ia, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileCode=request.getParameter("fileCode");
		String	choose =request.getParameter("choose");
		RESULT result = RESULT.ERROR;
		if (null == ia) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		if (ia.getCode() != null) {
			List<IndexAdvertisingAnnex> list = iaDAO.findAnnexByCode(ia.getCode());
			if(list != null){
				for(int i=0;i<list.size();i++){
					list.get(i).setCover(false);
					iaaDAO.upd(list.get(i));
				}
				if(choose!=null){
					IndexAdvertisingAnnex iaa = iaaDAO.get(Integer.parseInt(choose));
					if(iaa != null){
						iaa.setCover(true);
						iaaDAO.upd(iaa);
					}
				}
			
			}
			result = iaDAO.upd(ia);
			
		} else {
			Date date=new Date();
			ia.setPt(date);
			ia.setCu(cu_code(request));
			ia.setCt(date);
			ia.setDeleted(false);
			result = iaDAO.add(ia);
		}
		if (result == RESULT.SUCCESS) {
			List<Object> noDelCodes = new ArrayList<Object>();
			if (null != ia.getList() && ia.getList().size() > 0) {
				for (IndexAdvertisingAnnex iaa : ia.getList()) {
					noDelCodes.add(iaa.getCode());
				}
			}
			String[] afcs = request.getParameterValues(Parm.AFCS);
			if (null != afcs && afcs.length > 0) {
				StringBuffer codes = new StringBuffer();
				for (String code : afcs) {
					codes.append(code + Sys.COMMA);
				}
				codes.deleteCharAt(codes.length() - 1);
				List<FileInfo> list = iaDAO.findFileByCodes(codes.toString());
				if (null != list && list.size() > 0) {
					IndexAdvertisingAnnex temp = null;
					for (FileInfo fi : list) {
						temp = new IndexAdvertisingAnnex();
						temp.setExt(fi.getExt());
						temp.setIac(ia.getCode());
						temp.setName(fi.getName());
						temp.setSize(fi.getSize());
						temp.setSn(fi.getUuid());
						if(fileCode != null && Integer.parseInt(fileCode) == fi.getCode()){
							temp.setCover(true);
						}else{
							temp.setCover(false);
						}
						iaDAO.add(temp);
						noDelCodes.add(temp.getCode());
					}
				}
			}
			iaDAO.deleteAnnexNotInCodes(ia.getCode(), noDelCodes);
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	@Transactional
	@RequestMapping(Url.DETAIL)
	public ModelAndView detail(Integer code, HttpServletRequest request,
			HttpServletResponse response) {
		if (null != code) {
			IndexAdvertising ia = iaDAO.get(code);
			List<IndexAdvertisingAnnex> list = iaDAO.findAnnexByOccCode(code);
			request.setAttribute(Parm.IA, ia);
			request.setAttribute(Parm.LIST, list);
		}
		return new ModelAndView(Url.INDEX_ADVERTISING_DETAIL);
	}

	// 单个文件保存
	@Transactional
	@RequestMapping(Url.UPLOAD)
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile pohto = multipartRequest.getFile(Parm.UPLOAD);
		String type = request.getParameter(Parm.TYPE);
		String name = pohto.getOriginalFilename();
		if (isNotNull(name)) {
			String ext = name.substring(name.lastIndexOf(Sys.DOT) + 1);
			if (!ext.toUpperCase().equals(Sys.JPG)
					&& !ext.toUpperCase().equals(Sys.GIF)
					&& !ext.toUpperCase().equals(Sys.JPEG)
					&& !ext.toUpperCase().equals(Sys.BMP)
					&& !ext.toUpperCase().equals(Sys.PNG)
					&& !ext.toUpperCase().equals(Sys.XLSX)
					&& !ext.toUpperCase().equals(Sys.XLS)
					&& !ext.toUpperCase().equals(Sys.DOCX)
					&& !ext.toUpperCase().equals(Sys.DOC)
					&& !ext.toUpperCase().equals(Sys.PDF)
					&& !ext.toUpperCase().equals(Sys.PPT)
					&& !ext.toUpperCase().equals(Sys.RAR)
					&& !ext.toUpperCase().equals(Sys.ZIP)) {
				print(response, Msg.J_FILE_TYPE_ERROR);
				return;
			}
			name = name.substring(0, name.lastIndexOf(Sys.DOT));

			UUID u = UUID.randomUUID();
			String uuid = u.toString().replace("-", "");
			String path = (type.equals(Sys.FILE) ? indexadvertising_file_path : indexadvertising_photo_path) + uuid + Sys.DOT + ext;
			System.out.println(path
					+ "------------------------------------------------");
			String savePath = ConfigParm.getProjectPath() + path;
			FileOutputStream fo;
			int size = 0;

			try {
				fo = new FileOutputStream(savePath);
				size = pohto.getBytes().length;
				fo.write(pohto.getBytes());
				fo.close();
			} catch (Exception e) {
				print(response, Msg.J_ERROR);
				e.printStackTrace();
				throw new RuntimeException();
			}

			FileInfo f = new FileInfo();
			f.setDeleted(false);
			f.setExt(ext);
			f.setName(name);
			f.setUuid(uuid);
			f.setCt(new Date());
			if (type.equals(Sys.FILE)) {
				f.setType(Sys.B_ONE);
				f.setModule(Parm.INDEX_ADVERTISING_FILE);
			} else {
				f.setType(Sys.B_TWO);
				f.setModule(Parm.INDEX_ADVERTISING_PHOTO);
			}

			f.setCu(cu_code(request));
			f.setOc(cu_organCode(request));
			f.setSize(size);
			iaDAO.add(f);

			StringBuffer result = new StringBuffer();
			result.append("<script type=\"text/javascript\">");
			if (isNotNull(path)) {
				result.append("window.parent.CKEDITOR.tools.callFunction("
						+ request.getParameter("CKEditorFuncNum") + ",'" + path
						+ "',''" + ")");
				result.append("</script>");
				result.append(path);
			} else {
				result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
				result.append("</script>");
			}
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			print(response, result.toString());

		} else {
			print(response, Msg.J_ERROR);
		}
	}

	// 上传多个文件
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("files");

		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {

			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;

			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				System.out.println(mf.getOriginalFilename() + "--"
						+ mf.getName());
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG)
							&& !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG)
							&& !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));
					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = upload_path + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + "/" + path;
					FileOutputStream fo;
					int size = 0;

					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setUuid(uuid);
					f.setCt(new Date());
					f.setType(Sys.B_TWO);
					f.setModule(Parm.INDEX_ADVERTISING_ANNX);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					iaDAO.add(f);
					System.out.println(result);
					result.append("{\"name\":\"" + name + "\",\"code\":\""
							+ f.getCode() + "\",\"ext\":\"" + ext
							+ "\",\"size\":\"" + size + "\",\"path\":\"" + uuid
							+ Sys.DOT + ext + "\"},");
					System.out.println(result);
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[")
					.deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}
	@Autowired
	public void setIaaDAO(IndexAdvertisingAnnexDAO iaaDAO) {
		this.iaaDAO = iaaDAO;
	}
	@Autowired
	public void setIaDAO(IndexAdvertisingDAO iaDAO) {
		this.iaDAO = iaDAO;
	}
}
